package com.cn.boot.student.config;

import com.cn.boot.student.common.JwtAuthenticationTokenFilter;
import com.cn.boot.student.common.RestAuthenticationEntryPoint;
import com.cn.boot.student.common.RestfulAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//开启WebSecurity
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    protected void configure(HttpSecurity http) throws Exception {
        //csrf().disable()关闭跨站请求伪造攻击
        http.cors().and()
                .csrf().disable()
                .sessionManagement() //基于token，所以不需要  securityContext
                //请求资源成功后，线程结束，销毁内存中的令牌，释放资源
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/fonts/**", "/admin/user/**","/code").permitAll() //都可以访问
                .antMatchers("/users/**").hasRole("ADMIN") //需要相应的角色才能访问
                //注册不需要鉴权认证
                .antMatchers("/admin/user/register").anonymous()
                .antMatchers("/swagger-resources/**"
                        ,"/swagger-ui.html/**"
                        ,"/webjars/**"
                        ,"/user/login"
                        ,"/v2/api-docs"
                        ,"/swagger-resources/configuration/security"
                        ,"/swagger-resources/configuration/ui").anonymous()
                .anyRequest().authenticated() // 任何请求都需要认证
                .and()
//                .formLogin() //基于Form表单登录验证
//                .and()
//                .userDetailsService(userDetailsServiceBean());
                .userDetailsService(userDetailsService);
        //自定义登录界面
        //jwtAuthenticationTokenFilter解析token
        //UsernamePasswordAuthenticationFilter:账号密码认证过滤器比对是否有令牌，
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //添加自定义未授权和未登录结果返回
        http.exceptionHandling().accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);

    }


    //   这是将用户存入内存的第一种方式
//    @Autowired
//    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication() //认证信息存储到内存中
//                .passwordEncoder(passwordEncoder())
//                .withUser("user").password(passwordEncoder().encode("123456")).roles("ADMIN")
//                .authorities("wx:product:read","wx:product:delete");
//    }

    //   这是将用户存入内存的第二种方式
//    @Override
//    public UserDetailsService userDetailsServiceBean() throws Exception {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser(new User("admin",passwordEncoder().encode("123456"),     AuthorityUtils.createAuthorityList("wx:product:read","wx:product:delete")));
//        return manager;
//    }

    //   这是密码加密解密器 可以用于加密密码也可以用户对比原始密码与加密密码，你只需暴露，security会将你暴露的passwordEncoder 作为默认的
    //   passwordEncoder.encode()  用于加密密码
    //   passwordEncoder.matchs(原始密码，加密密码)  对比原始密码与加密密码
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
